<?php
// +----------------------------------------------------------------------
// | 腾讯云
// +----------------------------------------------------------------------

namespace helper\storage\driver;

use helper\storage\Driver;
use Qcloud\Cos\Client;
use QCloud\COSSTS\Sts;

class Cos implements Driver
{
    private array $config;

    private Client $handler;

    /**
     * COS constructor.
     * @param array $config
     */
    public function __construct(array $config)
    {
        $this->config  = $config;
        $this->handler = new Client(
            array(
                'region' => $config['region'], //设置一个默认的存储桶地域
                'schema' => $config['schema'], //协议头部，默认为http
                'credentials'=> array(
                    'secretId'  => $config['secretId'], // "云 API 密钥 SecretId";
                    'secretKey' => $config['secretKey'] //"云 API 密钥 SecretKey";
                )
            )
        );
    }

    /**
     * 上传文件
     * @param string $object
     * @param string $filePath
     * @return array
     */
    public function putFile(string $object, string $filePath): array
    {
        try {
            $bucket = $this->config['bucket'];
            $key = $object;
            $filePath = $filePath . '/' . $object;
            $fileSize = filesize($filePath);
            $file = fopen($filePath, "rb");
            if ($fileSize < 20 * 1024 * 1024) {
                ## putObject(上传接口，最大支持上传5G文件)
                $result = $this->handler->putObject(array(
                        'Bucket' => $bucket,
                        'Key' => $key,
                        'Body' => $file
                    )
                );
            } else {
                ## Upload(高级上传接口，默认使用分块上传最大支持50T)
                $result = $this->handler->Upload($bucket, $key, $file);
            }
            return ['code' => 0, 'msg'=> '', 'data' => json_decode($result, true)];
        } catch (\Exception $e) {
            // 请求失败
            return ['code' => 1, 'msg'=> $e->getMessage()];
        }
    }

    /**
     * 删除文件
     * @param string $object
     * @return array
     */
    public function deleteFile(string $object): array
    {
        try {
            $result = $this->handler->deleteObject(array(
                'Bucket' => $this->config['bucket'],
                'Key' => $object,
                //'VersionId' => 'exampleVersionId' //存储桶未开启版本控制时请勿携带此参数
            ));
            // 请求成功
            return ['code' => 0, 'msg'=> '', 'data' => json_decode($result, true)];
        } catch (\Exception $e) {
            // 请求失败
            return ['code' => 1, 'msg'=> $e->getMessage()];
        }
    }

    /**
     * 获取授权密钥
     * @return array
     * @throws \Exception
     */
    public function sts()
    {
        $sts    = new Sts();
        $config = array(
            'url'             => 'https://sts.tencentcloudapi.com/',
            'domain'          => 'sts.tencentcloudapi.com', // 域名，非必须，默认为 sts.tencentcloudapi.com
            'proxy'           => '',
            'secretId'        => $this->config['secretId'], // 固定密钥
            'secretKey'       => $this->config['secretKey'], // 固定密钥
            'bucket'          => $this->config['bucket'], // 换成你的 bucket
            'region'          => $this->config['region'], // 换成 bucket 所在园区
            'durationSeconds' => 1800, // 密钥有效期
            'allowPrefix'     => '*', // 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径，例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
            // 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
            'allowActions'    => array(
                // 简单上传
                'name/cos:PutObject',
                'name/cos:PostObject',
                // 分片上传
                'name/cos:InitiateMultipartUpload',
                'name/cos:ListMultipartUploads',
                'name/cos:ListParts',
                'name/cos:UploadPart',
                'name/cos:CompleteMultipartUpload'
            )
        );

        // 获取临时密钥，计算签名
        return $sts->getTempKeys($config);
    }
}